package com.home.task.impl;/**
 * @author chenxf
 * @date 2022/4/19 16:20
 */

import com.alibaba.fastjson.JSON;
import com.home.annotation.PolicyNewsProcesses;
import com.home.biz.PolicyNewsInfoBiz;
import com.home.biz.PolicySiteConfigBiz;
import com.home.entity.PolicyNewsInfo;
import com.home.entity.PolicySiteConfig;
import com.home.enums.FetchTypeEnum;
import com.home.service.PolicyNewsService;
import com.home.task.ITask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author chenxf
 * @date 2022/4/19 16:20
 */
@Slf4j
@Service
public class PolicyNewsTask  implements ITask {
    @Resource
    PolicySiteConfigBiz configBiz;
    @Resource
    PolicyNewsService newsService;
    @Resource
    PolicyNewsInfoBiz newsInfoBiz;
    @Override
    public boolean circlePlan() {
        PolicySiteConfig siteConfig=configBiz.fetchOneSite();
        log.info("site={}", JSON.toJSONString(siteConfig));
        if(ObjectUtils.isEmpty(siteConfig)){
            return false;
        }
        try {
            PolicyNewsInfo lastNews=newsInfoBiz.fetchLastNews(siteConfig.getId());
            String lastUrl=null;
            if(!ObjectUtils.isEmpty(lastNews)){
                lastUrl=lastNews.getFetchUrl();
            }
            FetchTypeEnum fetchTypeEnum= FetchTypeEnum.get(siteConfig.getSiteType());
            if(!fetchTypeEnum.equals(FetchTypeEnum.NONE)){
                List<PolicyNewsInfo> list=newsService.getProcessors(fetchTypeEnum).fetchPage(siteConfig,lastUrl);
                list.forEach(e->{
                    newsInfoBiz.insertSelective(e);
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        siteConfig.setFetchTime(new Date());
        configBiz.updateSelectiveById(siteConfig);
        return true;
    }

    @Override
    public String getName() {
        return "政策采集";
    }
}
